import string
import re
import sys
import os
import glob
import shutil
#import ply.lex as lex

def importCodeFile(sFileName, mapChar2Line):
    fFile = open(sFileName, 'r')
    sFileContent = ""
    iLineNumber = 0 
    while True:
        line = fFile.readline()
        if not line:
            break
        iLineNumber = iLineNumber + 1 
        for i in range( len(sFileContent), len(sFileContent) + len(line)):
            mapChar2Line[i] = iLineNumber
        sFileContent = sFileContent + line
    
    fFile.close()   
    return sFileContent



def commentExtract(sFileContent, mapChar2Line, iCount, sFileName , sDirectory, sDestDirectory ):
    reComment = re.compile('(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|(//.*)')
    match = reComment.search(sFileContent)
    relativePath = os.path.relpath(sFileName, sDirectory)
    listPathItems = relativePath.split('/')

    for item in listPathItems:
        sDestDirectory = sDestDirectory + "/" + item
        if not os.path.exists(sDestDirectory):
            os.makedirs(sDestDirectory)

    while match:
        fOutput = open(sDestDirectory + "/" + str(iCount) + ".txt", 'w')
        fOutput.write(sFileName)
        fOutput.write(": ")
        fOutput.write(str(mapChar2Line[match.start()]) + '\n')
        fOutput.write("Label: \n")
        fOutput.write(match.string[match.start():match.end()] + '\n' )
        fOutput.close()
        iCount = iCount + 1 
        match = reComment.search(sFileContent, match.end())

    return iCount


def findAllFiles(sDirectory, listFileNames ):
    if not os.path.isdir(sDirectory):
        listFileNames.append(sDirectory)
        return

    for sFile in glob.glob(os.path.join(sDirectory, '*') ):
        if os.path.isdir(sFile):
            findAllFiles(sFile, listFileNames)
        else:
            listFileNames.append(sFile)

def findCodeFiles(sDirectory):
    reCodeFileName = re.compile('^[^\r\n]*\.(cc|c|h)$')
    listFileNames = []
    findAllFiles(sDirectory, listFileNames )
    listCodeFiles = []
    for sFile in listFileNames:
        #print sFile
        match = reCodeFileName.match(sFile)
        if match:
            listCodeFiles.append(sFile)

    return listCodeFiles

   

def removeFiles(sDirectory):
    for sFile in glob.glob(os.path.join(sDirectory, '*')):
        if not os.path.isdir(sFile):
            os.unlink(sFile)
        else:
            shutil.rmtree(sFile)    


if __name__ == '__main__':
   if len(sys.argv) != 3:
       exit()
   listCodeFiles = findCodeFiles(sys.argv[1])
   originalDirectory = sys.argv[1]
   destDirectory = sys.argv[2]
   removeFiles(destDirectory)   

   iCount = 0
   for sFile in listCodeFiles:
       print sFile
       mapChar2Line = {}
       sFileContent = importCodeFile(sFile, mapChar2Line)
       iCount = commentExtract(sFileContent, mapChar2Line, iCount, sFile, originalDirectory, destDirectory )
       #break
   print iCount 
   
 
